<template>
  <div class="reset-password-container">
    <div class="reset-password-box">
      <div class="logo-section">
        <div class="logo-icon">
          <i class="icon-graduation-cap"></i>
        </div>
        <h2>农民技能提升就业培训大数据平台</h2>
        <p>重置密码</p>
      </div>
      
      <div v-if="!resetSuccess" class="reset-form">
        <div class="instruction">
          <i class="icon-info"></i>
          <p>请设置您的新密码，密码至少8位且包含大小写字母和数字。</p>
        </div>
        
        <form @submit.prevent="handleResetPassword">
          <!-- 错误提示 -->
          <div v-if="errorMessage" class="error-message">
            <i class="icon-alert-circle"></i>
            {{ errorMessage }}
          </div>
          
          <div class="form-group">
            <label>
              <i class="icon-lock"></i>
              新密码
            </label>
            <div class="password-input">
              <input
                v-model="resetForm.password"
                :type="showPassword ? 'text' : 'password'"
                required
                placeholder="请输入新密码"
                :disabled="loading"
                @blur="validatePassword"
              />
              <button 
                type="button" 
                @click="showPassword = !showPassword"
                class="password-toggle"
                :disabled="loading"
              >
                <i :class="showPassword ? 'icon-eye-off' : 'icon-eye'"></i>
              </button>
            </div>
            <span v-if="passwordError" class="field-error">{{ passwordError }}</span>
            <div class="password-strength">
              <div class="strength-bar">
                <div 
                  class="strength-fill" 
                  :class="passwordStrength.class"
                  :style="{ width: passwordStrength.percentage + '%' }"
                ></div>
              </div>
              <span class="strength-text" :class="passwordStrength.class">
                {{ passwordStrength.text }}
              </span>
            </div>
          </div>
          
          <div class="form-group">
            <label>
              <i class="icon-lock"></i>
              确认密码
            </label>
            <div class="password-input">
              <input
                v-model="resetForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                required
                placeholder="请再次输入新密码"
                :disabled="loading"
                @blur="validateConfirmPassword"
              />
              <button 
                type="button" 
                @click="showConfirmPassword = !showConfirmPassword"
                class="password-toggle"
                :disabled="loading"
              >
                <i :class="showConfirmPassword ? 'icon-eye-off' : 'icon-eye'"></i>
              </button>
            </div>
            <span v-if="confirmPasswordError" class="field-error">{{ confirmPasswordError }}</span>
          </div>
          
          <button type="submit" class="reset-btn" :disabled="loading || !isFormValid">
            <i v-if="loading" class="icon-loading"></i>
            {{ loading ? '重置中...' : '重置密码' }}
          </button>
        </form>
      </div>
      
      <div v-else class="success-section">
        <div class="success-icon">
          <i class="icon-check-circle"></i>
        </div>
        <h3>密码重置成功</h3>
        <p>您的密码已成功重置，现在可以使用新密码登录了。</p>
        
        <router-link to="/login" class="login-btn">
          立即登录
        </router-link>
      </div>
      
      <div class="back-to-login" v-if="!resetSuccess">
        <router-link to="/login">
          <i class="icon-arrow-left"></i>
          返回登录
        </router-link>
      </div>
      
      <div class="reset-footer">
        <p>© 2024 农民技能提升就业培训大数据平台</p>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-1"></div>
      <div class="decoration-2"></div>
      <div class="decoration-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const resetSuccess = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const errorMessage = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')

const resetForm = reactive({
  token: '',
  password: '',
  confirmPassword: ''
})

// API 基础配置
const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'

// 重置密码API调用
const resetPasswordAPI = async (token, newPassword) => {
  const response = await fetch(`${API_BASE_URL}/auth/reset-password`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      token,
      new_password: newPassword
    })
  })
  
  if (!response.ok) {
    const errorData = await response.json()
    throw new Error(errorData.detail || '重置失败')
  }
  
  return await response.json()
}

// 验证密码
const validatePassword = () => {
  const password = resetForm.password
  if (!password) {
    passwordError.value = '密码不能为空'
    return false
  }
  if (password.length < 8) {
    passwordError.value = '密码长度至少8位'
    return false
  }
  if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
    passwordError.value = '密码必须包含大写字母、小写字母和数字'
    return false
  }
  passwordError.value = ''
  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (resetForm.confirmPassword !== resetForm.password) {
    confirmPasswordError.value = '两次输入的密码不一致'
    return false
  }
  confirmPasswordError.value = ''
  return true
}

// 密码强度计算
const passwordStrength = computed(() => {
  const password = resetForm.password
  if (!password) return { percentage: 0, text: '', class: '' }
  
  let strength = 0
  
  if (password.length >= 8) strength += 20
  if (/[a-z]/.test(password)) strength += 20
  if (/[A-Z]/.test(password)) strength += 20
  if (/\d/.test(password)) strength += 20
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength += 20
  
  if (strength < 40) {
    return { percentage: strength, text: '弱', class: 'weak' }
  } else if (strength < 80) {
    return { percentage: strength, text: '中等', class: 'medium' }
  } else {
    return { percentage: strength, text: '强', class: 'strong' }
  }
})

// 表单验证
const isFormValid = computed(() => {
  return resetForm.password &&
         resetForm.confirmPassword &&
         !passwordError.value &&
         !confirmPasswordError.value
})

// 监听密码变化，重新验证确认密码
watch(() => resetForm.password, () => {
  if (resetForm.confirmPassword) {
    validateConfirmPassword()
  }
})

// 处理重置密码
const handleResetPassword = async () => {
  errorMessage.value = ''
  
  // 验证表单
  const isPasswordValid = validatePassword()
  const isConfirmPasswordValid = validateConfirmPassword()
  
  if (!isPasswordValid || !isConfirmPasswordValid) {
    errorMessage.value = '请检查表单中的错误信息'
    return
  }
  
  loading.value = true
  
  try {
    await resetPasswordAPI(resetForm.token, resetForm.password)
    resetSuccess.value = true
  } catch (error) {
    console.error('重置密码失败:', error)
    errorMessage.value = error.message || '重置失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 页面加载时获取token
onMounted(() => {
  const token = route.query.token
  if (!token) {
    errorMessage.value = '重置链接无效或已过期'
    return
  }
  resetForm.token = token
})
</script>

<style scoped>
/* 与忘记密码页面相似的样式 */
.reset-password-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.decoration-1,
.decoration-2,
.decoration-3 {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.decoration-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  right: 10%;
  animation: float 6s ease-in-out infinite;
}

.decoration-2 {
  width: 150px;
  height: 150px;
  bottom: 20%;
  left: 15%;
  animation: float 8s ease-in-out infinite reverse;
}

.decoration-3 {
  width: 100px;
  height: 100px;
  top: 60%;
  right: 20%;
  animation: float 10s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.reset-password-box {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 420px;
  position: relative;
}

.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
}

.logo-icon i {
  font-size: 36px;
  color: white;
}

.logo-section h2 {
  margin: 0 0 8px 0;
  color: #1F2937;
  font-size: 20px;
  font-weight: 600;
}

.logo-section p {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.instruction {
  background: #F0F9FF;
  border: 1px solid #BAE6FD;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.instruction i {
  color: #0EA5E9;
  margin-top: 2px;
  flex-shrink: 0;
}

.instruction p {
  margin: 0;
  color: #0F172A;
  font-size: 14px;
  line-height: 1.5;
}

.reset-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.error-message {
  background: #FEF2F2;
  border: 1px solid #FECACA;
  color: #DC2626;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group label i {
  color: #6B7280;
}

.form-group input {
  padding: 14px 16px;
  border: 2px solid #E5E7EB;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-group input:disabled {
  background-color: #F9FAFB;
  cursor: not-allowed;
}

.password-input {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6B7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.2s;
}

.password-toggle:hover:not(:disabled) {
  color: #374151;
}

.field-error {
  color: #DC2626;
  font-size: 12px;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
}

.strength-bar {
  height: 4px;
  background: #E5E7EB;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 4px;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: #EF4444;
}

.strength-fill.medium {
  background: #F59E0B;
}

.strength-fill.strong {
  background: #10B981;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
}

.strength-text.weak {
  color: #EF4444;
}

.strength-text.medium {
  color: #F59E0B;
}

.strength-text.strong {
  color: #10B981;
}

.reset-btn {
  padding: 14px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.reset-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

.reset-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.success-section {
  text-align: center;
}

.success-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #10B981, #059669);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
  box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
}

.success-icon i {
  font-size: 36px;
  color: white;
}

.success-section h3 {
  margin: 0 0 16px 0;
  color: #1F2937;
  font-size: 24px;
  font-weight: 600;
}

.success-section p {
  margin: 0 0 24px 0;
  color: #6B7280;
  font-size: 14px;
  line-height: 1.5;
}

.login-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 14px 24px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: white;
  text-decoration: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.login-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

.back-to-login {
  margin-top: 32px;
  text-align: center;
  padding-top: 24px;
  border-top: 1px solid #E5E7EB;
}

.back-to-login a {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: #6B7280;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.2s;
}

.back-to-login a:hover {
  color: #4F46E5;
}

.reset-footer {
  margin-top: 20px;
  text-align: center;
}

.reset-footer p {
  margin: 0;
  color: #6B7280;
  font-size: 12px;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .reset-password-container {
    padding: 16px;
  }
  
  .reset-password-box {
    padding: 32px 24px;
  }
  
  .logo-section h2 {
    font-size: 18px;
  }
}
</style>